//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    products:[
      // { id: 1, sku_name: '来伊份猪肉脯高蛋白酥', price: 9.80,orinprice:12.80,inventory:999},
      // { id: 2, sku_name: '来伊份零食畅享盲盒月卡', price: 15.00,orinprice:25.80,inventory:10},
      // { id: 3, sku_name: '来伊份权益会员8折', price: 5.00,orinprice:12.80,inventory:999},
      // { id: 6, sku_name: '来伊份碧根果仁100g', price: 15.00,orinprice:25.80,inventory:0},
    ],
    currentData:{},
    currentNum:1,
    showAuthPopup: false,

    phone:'',
    uid:'',
    userId:'',
    equityNum:0,
    showModal: false,
    modalAnimation: null,
    maskAnimation: null
  },
  //加入购物车
  addCar: function(e) {
    let productId=e.currentTarget.dataset.id;
    let _this=this;
    wx.request({
      url:app.globalData.onlineUrl+"/getProInventory",
      header:{'content-type': 'application/json'},
      method:"POST",
      data:{
        id:productId,
      },
      dataType:"json",
      complete:function(result) {
        console.log(19998,result.data.data[0].inventory);
        if(_this.data.currentNum>result.data.data[0].inventory){
          wx.showToast({
            title: '库存不足',
            icon: 'error',
            duration: 2000
          })
        }else{
          wx.request({
            url:app.globalData.onlineUrl+"/addBuyCar",
            header:{'content-type': 'application/json'},
            method:"POST",
            data:{
              phone:_this.data.phone,
              productId:productId,
              buyNum:_this.data.currentNum
            },
            dataType:"json",
            complete:function(result) {
              _this.hideModal();
              wx.showToast({
                title: '加入成功',
                image: '/images/123.png',
                duration: 2000,
                mask:true
              })
              app.getBuyCarNum();
            }
          })
        }
        
      }
    })
  },
  //搜索
  handleFocus: function() {
    wx.navigateTo({
      url: '/pages/search/search'
    })
  },
  // 增加数量
  increaseQuantity() {
    if(this.data.currentNum<this.data.currentData.inventory){
      this.data.currentNum++;
      this.setData({
        currentNum:this.data.currentNum
      });
    }
  },

  // 减少数量
  decreaseQuantity() {
    if(this.data.currentNum>1){
      this.data.currentNum--;
      this.setData({
        currentNum:this.data.currentNum
      });
    }
  },
//2.0跳转现金购
gotoCashPurchase:function(){
  wx.navigateTo({
    url: '/pages/cashPurchase/cashPurchase'
  })
},
//2.0跳转话费购
gotoPhonebillPurchase:function(){
  wx.navigateTo({
    url: '/pages/phonebillPurchase/phonebillPurchase'
  })
},
//2.0跳转商品详情
gotoProductDetail:function(e){
  wx.navigateTo({
    url: '/pages/productDetails/productDetails?id='+e.currentTarget.dataset.id
  })
},
// 2.0打开弹窗
showModal(e) {
  if(this.data.phone){
    this.setUser();
    // 创建动画
    const modalAnimation = wx.createAnimation({
      duration: 300,
      timingFunction: 'ease-out'
    })
    
    const maskAnimation = wx.createAnimation({
      duration: 300,
      timingFunction: 'ease-out'
    })

    // 执行动画
    maskAnimation.opacity(1).step()
    modalAnimation.translateY(0).step()
    const currentData = this.data.products.find(item => item.id === e.currentTarget.dataset.id);
    this.setData({
      currentNum:1,
      currentData:currentData,
      showModal: true,
      modalAnimation: modalAnimation.export(),
      maskAnimation: maskAnimation.export()
    })
  }else{
    this.setData({ showAuthPopup: true });
  }
  
},

hideModal() {
  const modalAnimation = wx.createAnimation({
    duration: 250,
    timingFunction: 'ease-in'
  })
  
  const maskAnimation = wx.createAnimation({
    duration: 250,
    timingFunction: 'ease-in'
  })

  maskAnimation.opacity(0).step()
  modalAnimation.translateY('100%').step()

  this.setData({
    modalAnimation: modalAnimation.export(),
    maskAnimation: maskAnimation.export()
  })

  // 延迟隐藏保证动画完成
  setTimeout(() => {
    this.setData({ showModal: false })
  }, 250)
},
gotoProductDetail:function(e){
  wx.navigateTo({
    url: '/pages/productDetails/productDetails?id='+e.currentTarget.dataset.id
  })
},
//移动banner
  jumpYd:function(){
    wx.navigateTo({
      url: '/pages/ydhf/ydhf?url=https://dev.coc.10086.cn/coc3/canvas/rightsmarket-h5-canvas/online/hzhbjh?channelCode=P00000111642'
    })
  },
  //获取商品列表
  getProduct:function(){
    let _this=this;
    wx.request({
      url:app.globalData.onlineUrl+"/productNew/list",
      header:{'content-type': 'application/json'},
      method:"POST",
      data:{type:3},
      dataType:"json",
      complete:function(result) {
        console.log(9999,result.data.data);
        let data=result.data.data;
        _this.setData({
          products:data,
        })
      }
    })
  },
  onLoad: function () {
    let _this=this;
    if(wx.getStorageSync('phone')){
      _this.getUserVip()
    }
    //获取openid
    // wx.login({
    //   //成功放回
    //   success:(res)=>{
    //     console.log(res);
    //     console.log(res.code);
    //       wx.request({
    //         url:app.globalData.onlineUrl+"/getOpenid",
    //         header:{'content-type': 'application/json'},
    //         method:"POST",
    //         data:{code:res.code},
    //         dataType:"json",
    //         complete:function(res) {
    //             console.log(89889,res);
    //             var obj = {};
    //               obj.openid = res.data.data;
    //               // obj.expires_in = Date.now() + res.data.expires_in;
    //             //存储openid
    //               wx.request({
    //                 url:app.globalData.onlineUrl+"/login/state",
    //                 header:{'content-type': 'application/json'},
    //                 method:"GET",
    //                 data:{openId:obj.openid},
    //                 dataType:"json",
    //                 complete:function(result) {
    //                   console.log(1123,result.data.data);
    //                   wx.setStorageSync('openid', obj.openid);
    //                   let data=result.data.data;
    //                   if(data.length!=0){
    //                     _this.setData({
    //                       phone:data[0].phone,
    //                       uid:data[0].uid,
    //                       userId:data[0].id,
    //                     })
    //                     wx.setStorageSync('phone',data[0].phone);
    //                     wx.setStorageSync('uid',data[0].uid);
    //                     wx.setStorageSync('userId',data[0].id);
    //                   }
    //                 }
    //               })
    //         }
    //       })
    //   }
    // })
  },
  setOrder:function(){
    let _this=this;
    wx.request({
      url: app.globalData.onlineUrl+'/getNewOrder', 
      method: 'POST',
      data: {
        phone:_this.data.phone
      },
      success: function(res) {
        console.log(123,res.data.data);
        let orders=res.data.data;
        orders.map(order => {
          if (order.state === 0 && order.order_type === 2 ) {
            const now = Date.now();
            const createTime = new Date(order.create_time).getTime();
            order.endTime=createTime + 600000,
            order.goodsJson = JSON.parse(order.goodsJson);
            const remaining = order.endTime - now;
            if (remaining <= 0) {
              _this.updateNewOrder(order.orderId,4)
              _this.updateInventory(order.goodsJson);
              _this.backCoupon(order);
            }
          }
        })
      },
      fail: function(err) {
      },
      complete: function() {}
    });
  },
  //处理库存
updateInventory(goodsList){
  goodsList.forEach(good => {
    this.setInventory(good.productId, good.buyNum);
  });
},
//修改库存
setInventory(id,buyNum){
  let _this=this;
  wx.request({
    url: app.globalData.onlineUrl+'/quitInventory', 
    method: 'POST',
    data: {
      id:id,
      buyNum:buyNum,
    },
    success: function(res) {
      console.log("库存处理成功");
    },
    fail: function(err) {
    },
    complete: function() {}
  });
},
backCoupon(order){
  console.log(1,order);
  if(order.couponId){
    let _this=this;
    wx.request({
      url: app.globalData.onlineUrl+'/backCoupon',
      data: {
        phone:wx.getStorageSync('phone'),
        id:order.couponId,
      },
      header:{'content-type': 'application/json'},
      method:"POST",
      dataType:"json",
      success: res => {
      }
    })
  }
},
//修改订单状态
updateNewOrder: function (id,state) {
  console.log(id,state)
  let _this=this;
  wx.request({
    url: app.globalData.onlineUrl+'/updateNewOrder', 
    method: 'POST',
    data: {
      orderId:id,
      state:state,
    },
    success: function(res) {
      console.log(325)
    },
    fail: function(err) {
    },
    complete: function() {}
  });
},
  onShow() {
    app.getBuyCarNum();
    wx.showShareMenu({
      withShareTicket: true
    })
    this.getTabBar().setData({
      PageCur: 'index'
    })
    this.setData({
      phone:wx.getStorageSync('phone'),
    })
    this.getProduct();
    console.log(this.data.phone);
    // this.setData({
    //   showAuthPopup:!this.data.phone,
    // })
    //处理订单
    this.setOrder();
  },
/**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    console.log(12242);
    return {
      title: '来伊份零食会员权益',
      path: 'pages/index/index',
      imageUrl: '/images/share.png'
    }
  },
  onGetPhoneNumber(e) {
    if (e.detail.errMsg === 'getPhoneNumber:ok') {
      const { encryptedData, iv } = e.detail;
      wx.login({
        success: res => {
          if (res.code) {
            // 发送 res.code 到后台换取 openid, session_key, unionid
            wx.request({
              url: app.globalData.onlineUrl+"/getUserPhone", // 替换为你的服务器地址
              header:{'content-type': 'application/json'},
              method: 'POST',
              data: {
                code: res.code,
                encryptedData:encryptedData,
                iv:iv,
              },
              success: (response) => {
                console.log(10086,response.data.data.phoneNumber);
                // 存储用户信息
                wx.setStorageSync('phone', response.data.data.phoneNumber);
                wx.setStorageSync('openid', response.data.data.openId);
                this.setUser();
                this.setData(
                  {
                    phone:wx.getStorageSync('phone'),
                    showAuthPopup:false
                  }
                )
              }
            });
          } else {
            console.log('登录失败！' + res.errMsg);
          }
        }
      });
    } else {
      // 用户拒绝授权时的处理（根据合规要求，建议允许用户取消）
      wx.showToast({ 
        title: '需要授权手机号才能使用完整服务', 
        icon: 'none',
        duration: 2000
      });
    }
  },
  setUser:function(){
    let _this=this;
    wx.request({
      url:app.globalData.onlineUrl+"/setUser",
      header:{'content-type': 'application/json'},
      method:"POST",
      data:{
        phone:wx.getStorageSync('phone'),
        openId:wx.getStorageSync('openid')
      },
      dataType:"json",
      complete:function(result) {
        console.log("用户信息更新成功");
      }
    })
  },
  onClosePopup() {
    this.setData({ showAuthPopup: false });
  },
  getUserVip(){
    let _this=this;
    wx.request({
      url:app.globalData.onlineUrl+"/getUserVip",
      header:{'content-type': 'application/json'},
      method:"POST",
      data:{
        phone:wx.getStorageSync('phone')
      },
      dataType:"json",
      success:function(result) {
        //存储用户会员信息
        if(result.data.data.length>0){
          wx.setStorageSync('vipFlag',true)
          wx.setStorageSync('vip',JSON.stringify(result.data.data))
        }else{
          wx.setStorageSync('vipFlag',false)
        }
        
      }
    })
  }


})
